'use strict';
const util = require('../../lib/util.js');
module.exports = async (job, done, app) => {
  const start = Date.now();
  const data = job.data;
  const resultInfo = {};
  let where = 'deleted_at is null ';
  if (data.source) {
    if (Array.isArray(data.source)) {
      where += ` and source in ("${data.source.join('","')}")`;
    } else {
      where += ` and source=${data.source}`;
    }
  }
  for (const categorie_id of data.categorie_ids) {
    const sqlQuery = [];
    for (const textInfo of data.texts) {
      const sql = `SELECT word FROM tort_words_${categorie_id}s WHERE  ${where} and instr(:word,concat(' ',word,' '))`;
      sqlQuery.push(app.model.query(sql, {
        replacements: {
          word: textInfo.text,
        },
        type: app.Sequelize.QueryTypes.SELECT, // 指定查询类型
      }).then(async wrods => {
        resultInfo[textInfo.key] = resultInfo[textInfo.key] || {};
        for (const fWord of wrods) {
          if (resultInfo[textInfo.key][fWord.word]) {
            resultInfo[textInfo.key][fWord.word]++;
          } else {
            resultInfo[textInfo.key][fWord.word] = 1;
          }
        }
        return true;
      }));
    }
    await Promise.all(sqlQuery);
  }
  await app.redis.set(`detection-result:${data.sign}`, JSON.stringify(resultInfo), 'EX', 48 * 60 * 60);
  if (data.callback_url) {
    for (const [ key, info ] of Object.entries(resultInfo)) {
      const respes = await app.erpPost('save_cite_tort_log', {
        json_content: JSON.stringify({
          goods_id: key,
          word: Object.keys(info),
        }),
      }).catch(err => {
        app.logger.error(`callback_url:save_cite_tort_log------error:${err.message}`);
      });
      try {
        app.logger.info(`callback_url:save_cite_tort_log-----respes:${JSON.stringify(respes)}`);
      } catch (err) {
        app.logger.info(`callback_url:save_cite_tort_log-----respes:${respes}`);
      }
    }
  }
  const end = Date.now();
  app.logger.info(`${data.sign}:start(ms):${start} end(ms):${end}  jg:${end - start} ms result:${JSON.stringify(resultInfo)}`);
  return Promise.resolve(done());
};
